package com.alonsoruibal.chess.bitboard;

public class Gen {
	
	
	public static int magicTransform(long b, long magic, byte bits) {
		  return (int)((b * magic) >>> (64 - bits));
	}
	
	static long squareAttackedAuxSliderMask(long square, int shift, long border) {
		long ret = 0;
		while ((square & border) == 0) {
			if (shift > 0) square <<= shift; else square >>>= -shift;
			if ((square & border) == 0) ret |= square;
		}
		return ret;
	}
	
	/**
	 * Fills pieces from a mask. Neccesary for magic generation
	 * variable bits is the mask bytes number
	 * index goes from 0 to 2^bits
	 */
	static long generatePieces(int index, int bits, long mask) {
		  int i;
		  long lsb;
		  long result = 0L;
		  for (i = 0; i < bits; i++) {
			lsb = mask & (-mask);
		    mask ^= lsb; // Deactivates lsb bit of the mask to get next bit next time
		    if ((index & (1 << i)) != 0) result |= lsb; // if bit is set to 1
		  }
		  return result;
	}

	/**
	 * Attacks for sliding pieces
	 */
	static long checkSquareAttackedAux(long square, long all, int shift, long border) {
		long ret = 0;
		while ((square & border) == 0) {
			if (shift>0) square <<= shift; else square >>>= -shift;
			ret |= square;
			// If we collide with other piece
			if ((square & all) != 0) break;
		}
		return ret;
	}

}
